/* eslint-disable no-undef */
/* eslint-disable no-unused-vars */

import L from 'leaflet';
import 'leaflet/dist/leaflet.css';
import 'leaflet.pm';
import 'leaflet.pm/dist/leaflet.pm.css';
// import "leaflet.wmts";
import '@/lib/leaflet-geoman/leaflet-geoman.min.js';
import '@/lib/leaflet-geoman/leaflet-geoman.css';
import { Dialog } from 'vant';
import { Toast } from 'vant';
import api from '@/api/addfiled';
import { workDistance, calculateAreaInMu } from '@/utils/index';
import coordtransform from '@/utils/coordtransform';
import { getAppLocation } from '@/utils/jssdkUtil';
import { GPS } from '@/utils/gps';

export default {
  name: 'CanvasMap',
  computed: {},
  props: {
    editBoundaries: {
      type: Array,
      default: () => {}
    },
    center: {
      type: Object,
      default: () => {}
    },
    isEdtior: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      map: null,
      searchVal: '',
      searboxFalg: '',
      showtips: true,
      graphics: [],
      showEnclosure: true,
      showEmpy: false,
      showNext: false,
      canvasCenter: [],
      zoom: 18,
      perimeter: 0,
      area: 0,
      altitude: 0,
      slope: 0,
      sicanvasDom: false,
      seachList: [],
      searchMarker: null,
      showempyOne: false,
      mymap2: null,
      map2Layer: null,
      grounpId: this.$route.query.grounpId,
      address: '',
      latlngs: [], // 存入当前跑马画田的坐标集合
      drawObj: null, // 跑马画田对象
      drawObjGon: null,
      showNextRun: false
    };
  },
  components: {},
  methods: {
    // 初始化地图
    // 注意，示例图层使用的是高德的图层，可能与需要的坐标系不一样，需要与后台确定好是什么坐标系进行坐标系转换后再提交到后台
    initMap() {
      const _t = this;
      var googlelayer = L.tileLayer(
        'https://webst02.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}',
        {
          maxZoom: 18,
          updateWhenIdle: true,
          crossOrigin: true,
          reuseTiles: false,
          unloadInvisibleTiles: true
        }
      );
      var image = L.layerGroup([googlelayer]);
      const map = L.map('drawField', {
        minZoom: 3,
        maxZoom: 18,
        center: [31.80452471, 118.4253323],
        zoom: _t.zoom,
        layers: [image],
        zIndex: 6,
        zoomControl: false,
        attributionControl: false,
        crs: L.CRS.EPSG3857
      });
      map.on('locationfound', function(e) {
        var radius = e.accuracy / 2;
        var marker = L.marker(e.latlng).addTo(map).bindPopup('您的当前位置');
        L.circle(e.latlng, radius).addTo(map);
      });

      map.on('locationerror', function(e) {
        console.log('定位出错=====>', e);
      });

      _t.map = map;
      _t.getLngLatLocation();
      if (this.isEdtior) {
        this.editMap();
      }
    },

    seachInput(val) {
      this.searboxFalg = val;
      this.onSearch(val, 0);
    },
    // 点击搜索结果
    clickSearchVal(index) {
      var myIcon = L.icon({
        iconUrl: require('@/assets/fieldManage/dian.png'),
        iconSize: [30, 30]
      });

      // this.seachList = []
      this.searboxFalg = '';
      this.searchVal = this.seachList[index].address;
      var arrr = this.seachList[index].location.split(',');
      // 国测局坐标 (gcj02坐标)
      var xAxis_gcj02 = arrr[0];
      var yAxis_gcj02 = arrr[1];
      // 国测局坐标转wgs84坐标
      var gcj02towgs84 = coordtransform.gcj02towgs84(xAxis_gcj02, yAxis_gcj02);
      // wgs84坐标
      var xAxis_wgs84 = gcj02towgs84[0];
      var yAxis_wgs84 = gcj02towgs84[1];
      // 使用给定的动画选项设置地图视图（地理中心和缩放）。
      this.map.setView([yAxis_wgs84, xAxis_wgs84], 18);
      if (this.searchMarker) {
        this.searchMarker.remove();
        this.searchMarker1.remove();
      }
      this.searchMarker = L.marker([yAxis_wgs84, xAxis_wgs84], {
        icon: myIcon
      });
      this.searchMarker.addTo(this.map);
      this.searchMarker.on('dblclick', () => {
        this.map.setView([yAxis_wgs84, xAxis_wgs84], 18);
      });
    },
    /**
     *  获取地址模糊查询列表
     *  @param keywords 关键词
     *  @param type 【0、监测用户 input 框输入 1、回车或搜索按钮确认
     */
    // 搜索
    onSearch(keywords, type = 1) {
      const val = type == 1 ? this.searchVal : keywords;
      const _t = this;
      var url =
        'https://restapi.amap.com/v3/place/text?keywords=' +
        val +
        '&output=JSON&key=83b6ca3017e78514ff4ce12ea734716f'; // 需要填写正确的高德地图的key
      _t.seachList = [];
      $.ajax({
        url: url,
        success: function(result) {
          // commonAjax.ajaxSubmit(url, "GET", "", function (result) {
          if (result.status === '1') {
            var arr = result.pois;
            for (var i = 0; i < arr.length && i < 10; i++) {
              var item = {
                address: arr[i].cityname + arr[i].adname + arr[i].address,
                name: arr[i].name,
                location: arr[i].location
              };
              _t.seachList.push(item);
            }
          } else {
            // errMsg.showError('1001');
          }
        }
      });
    },
    // 圈地
    enclosure() {
      this.general();
      // Dialog.confirm({
      //     title: '圈田',
      //     message: '请选择圈田方式',
      //     confirmButtonText: '圈田',
      //     cancelButtonText: '跑马圈田'
      // }).then(() => {
      //     // on confirm
      //     this.general()
      // }).catch(() => {
      //     // on cancel
      //     this.enclosureRun()
      // });
    },
    nextRun() {
      this.map.pm.disableGlobalEditMode();
      this.getAreaPerimeter(
        this.drawObjGon.getCenter().lng,
        this.drawObjGon.getCenter().lat,
        this.drawObjGon._latlngs
      );
    },
    enclosureRun() {
      const _t = this;
      getAppLocation((data) => {
        if (data) {
          _t.showempyOne = true;
          _t.showEnclosure = false;
          var corner2 = L.latLng(data.latitude, data.longitude);
          _t.latlngs.push(corner2);
          _t.drawObj = L.polyline(_t.latlngs, {
            color: 'rgb(51, 136, 255)'
          }).addTo(this.map);
          _t.drawObj.pm.enable({
            allowSelfIntersection: true
          });
          _t.drawObj.on('pm:edit', (obj) => {
            _t.latlngs = obj.target._latlngs;
            console.log(_t.latlngs, obj.target._latlngs);
          });
          _t.timer = setInterval(() => {
            getAppLocation((data) => {
              if (data) {
                // _t.map.removeLayer(_t.drawObj)
                const abDistance = _t.getLatLngDistance(
                  _t.latlngs[_t.latlngs.length - 1].lat,
                  _t.latlngs[_t.latlngs.length - 1].lng,
                  ...[data.latitude, data.longitude]
                );
                const aaDistance = _t.getLatLngDistance(
                  _t.latlngs[0].lat,
                  _t.latlngs[0].lng,
                  data.latitude,
                  data.longitude
                );
                if (_t.latlngs.length > 3 && aaDistance < 15) {
                  //
                  _t.map.removeLayer(_t.drawObj);
                  _t.drawObjGon = L.polygon(_t.latlngs, {
                    color: 'rgb(51, 136, 255)'
                  }).addTo(_t.map);
                  _t.drawObjGon.pm.enable({
                    allowSelfIntersection: false
                  });
                  _t.drawObjGon.on('pm:edit', (obj) => {
                    _t.latlngs = obj.target._latlngs[0];
                  });
                  _t.showNextRun = true;
                  clearInterval(_t.timer);
                  //   _t.getAreaPerimeter(workingLayer.layer.getCenter().lng, workingLayer.layer.getCenter().lat, workingLayer.layer._latlngs)
                } else if (abDistance >= 15) {
                  var corner2 = L.latLng(data.latitude, data.longitude);
                  _t.latlngs.push(corner2);
                  // 当前点和上一个点大于20m 在地图做绘制
                  // _t.drawObj = L.polyline(_t.latlngs).addTo(this.map);
                  _t.drawObj.addLatLng(corner2);
                  _t.drawObj.pm.enable({
                    allowSelfIntersection: false
                  });
                  _t.drawObj.on('pm:edit', (obj) => {
                    _t.latlngs = obj.target._latlngs;
                  });
                }
              }
            });
          }, 3000);
        }
      });
    },

    // 判断两个坐标之间的距离
    getLatLngDistance(lat1, lng1, lat2, lng2) {
      var radLat1 = (lat1 * Math.PI) / 180.0;
      var radLat2 = (lat2 * Math.PI) / 180.0;
      var a = radLat1 - radLat2;
      var b = (lng1 * Math.PI) / 180.0 - (lng2 * Math.PI) / 180.0;
      var s =
        2 *
        Math.asin(
          Math.sqrt(
            Math.pow(Math.sin(a / 2), 2) +
              Math.cos(radLat1) *
                Math.cos(radLat2) *
                Math.pow(Math.sin(b / 2), 2)
          )
        );
      s = s * 6378.137; // EARTH_RADIUS;
      s = Math.round(s * 10000) / 10;
      return s; // 返回 M
    },

    // 普通圈田
    general() {
      const _t = this;
      this.map.pm.enableDraw('Polygon', {
        snappable: true,
        snapDistance: 20,
        tooltips: false
      });
      this.showempyOne = true;
      this.showEnclosure = false;
      this.map.on('pm:create', (workingLayer) => {
        _t.graphics.push(workingLayer);
        _t.getAreaPerimeter(
          workingLayer.layer.getCenter().lng,
          workingLayer.layer.getCenter().lat,
          workingLayer.layer._latlngs
        );
      });
    },
    /* 根据图层边界计算周长和面积 */
    getAreaPerimeter(centerlng, centerlat, _latlngs) {
      const _t = this;
      _t.sicanvasDom = true;
      // const graphic = LMapUtil.getGraphics(workingLayer);
      _t.canvasCenter = {
        lng: centerlng,
        lat: centerlat
      };
      _t.getAddressByAxis(centerlng, centerlat);
      _t.showNextRun = false;
      _t.showEnclosure = false;
      _t.showEmpy = true;
      _t.showNext = true;
      this.showempyOne = false;
      var boundaries = _latlngs;
      _t.boundaries = _latlngs;
      _t.computedAreaPerimeter(boundaries);
    },

    /* 计算面积和周长 */
    computedAreaPerimeter(boundaries) {
      const _t = this;
      // 面积
      const area = calculateAreaInMu(boundaries);
      _t.area = isNaN(area) ? 0 : area;

      const latlngs = boundaries[0];
      const axises = [];
      const axises2 = [];
      for (const i in latlngs) {
        axises.push(latlngs[i]['lng']);
        axises.push(latlngs[i]['lat']);
      }
      for (const i in latlngs) {
        const lngLat = { longitude: null, latitude: null };
        lngLat.longitude = latlngs[i]['lng'];
        lngLat.latitude = latlngs[i]['lat'];
        axises2.push(lngLat);
        // axises2.push([latlngs[i]['lng'],latlngs[i]['lat']]);
        // axises2.push(LngLat[latlngs[i]['lng'],latlngs[i]['lat']]);
      }
      // 计算周长
      const perimeter = workDistance(axises2);
      _t.perimeter = Math.floor(perimeter * 100) / 100;
      _t.getAreaMpre(_t.canvasCenter, axises, latlngs);
    },
    /* 编辑地图 */
    editMap() {
      this.boundaries = this.editBoundaries;
      this.canvasCenter = this.center;
      this.computedAreaPerimeter(this.editBoundaries);
      setTimeout(() => {
        const pLayer = L.polygon(this.editBoundaries, {
          fillOpacity: 0.5,
          fillColor: 'green'
        }).addTo(this.map);

        this.map.fitBounds(this.editBoundaries); // 图形在中心

        this.map.pm.enableGlobalEditMode({
          snappable: true,
          snapDistance: 100
        });

        // enable Edit Mode
        pLayer.pm.enable({
          // allowSelfIntersection: false,
        });

        pLayer.on('pm:snapdrag', (workingLayer) => {
          this.getAreaPerimeter(
            workingLayer.layer.getCenter().lng,
            workingLayer.layer.getCenter().lat,
            workingLayer.layer._latlngs
          );
        });
      }, 1000);
    },
    /* 确认重新画田完成 */
    onConfirmEdit() {
      const area = Number(this.area);
      if (area > 5000) {
        Dialog.confirm({
          title: '提示',
          message: '田块面积不可超过5000亩！',
          showCancelButton: false
        }).then(() => {
          this.onCancelEdit();
        });
        return false;
      }
      this.$emit('drawMapComp', {
        area: this.area,
        altitude: this.altitude,
        slope: this.slope,
        perimeter: this.perimeter,
        center: this.canvasCenter,
        boundaries: this.boundaries,
        grounpId: this.grounpId,
        address: this.address
      });
    },
    /* 取消重新画田 */
    onCancelEdit() {
      this.$emit('drawMapComp', {}, true);
    },
    // 获取 海拔 坡度
    getAreaMpre(center, axises) {
      const params = {
        lng: center.lng.toString(),
        lat: center.lat.toString(),
        hash: 'x'
      };

      api.getAltitude(params).then((res) => {
        if (res.code == 0) {
          this.altitude = res.resData ? parseFloat(res.resData).toFixed(3) : 0;
        }
      });

      api.getSlope(params).then((res) => {
        if (res.code == 0) {
          this.slope = res.resData ? parseFloat(res.resData).toFixed(3) : 0;
        }
      });
    },
    empyOne() {
      this.showempyOne = false;
      this.showEnclosure = true;
      this.map.pm.disableDraw('Polygon');
      if (this.drawObjGon) {
        this.map.removeLayer(this.drawObjGon);
        this.latlngs = [];
      }

      if (this.drawObj) {
        this.map.removeLayer(this.drawObj);
        this.latlngs = [];
      }
      this.showNextRun = false;
      clearInterval(this.timer);
    },

    // 下一步
    next() {
      const area = Number(this.area);
      if (area > 5000) {
        Dialog.confirm({
          title: '提示',
          message: '田块面积不可超过5000亩，请重新圈田！',
          showCancelButton: false
        }).then(() => {
          this.empy();
        });
        return false;
      }
      this.$emit('drawMapComp', {
        area: this.area,
        altitude: this.altitude,
        slope: this.slope,
        perimeter: this.perimeter,
        center: this.canvasCenter,
        boundaries: this.boundaries,
        grounpId: this.grounpId,
        address: this.address
      });
    },

    // 清除绘制
    empy() {
      this.graphics.forEach((graphic) => {
        console.log(graphic.layer);
        this.map.removeLayer(graphic.layer);
      });
      if (this.drawObjGon) {
        this.map.removeLayer(this.drawObjGon);
        this.latlngs = [];
      }
      if (this.drawObj) {
        this.map.removeLayer(this.drawObj);
        this.latlngs = [];
      }
      clearInterval(this.timer);
      this.sicanvasDom = false;
      this.showEnclosure = true;
      this.showEmpy = false;
      this.showNext = false;
      this.showempyOne = false;
      this.canvasCenter = [];
      this.showNextRun = false;
    },
    // 定位
    location(n, l) {
      const _t = this;
      // 点位icon
      if (_t.myIcon1) {
        _t.map.flyTo([l, n]);
        _t.map.setView([l, n], 18);
        return;
      }

      _t.myIcon1 = L.icon({
        iconUrl: require('@/assets/fieldManage/dizhi.png'),
        iconSize: [28, 35]
      });
      this.searchMarker1 = L.marker([l, n], {
        icon: _t.myIcon1
      });
      _t.searchMarker1.addTo(this.map);
      _t.map.setView([l, n], 18);
      _t.map.flyTo([l, n]);
    },
    flyMap() {
      if (this.canvasCenter.length <= 0) {
        Toast('请先圈地，在使用此功能');
      } else {
        this.map.flyTo(this.canvasCenter);
      }
    },
    addZomm() {
      this.map.zoomIn();
    },
    recZoom() {
      this.map.zoomOut();
    },
    /* 当前位置 */
    getLocation() {
      const _t = this;
      this.getLngLatLocation();
    },
    /** 获取地址，坐标逆编码 */
    getAddressByAxis(xAxis, yAxis) {
      var latlng = GPS.gcj_encrypt(yAxis, xAxis);

      const _t = this;
      var url =
        'https://restapi.amap.com/v3/geocode/regeo?key=*****' + // 用高德坐标逆编码，获取地址信息 // 需要填写正确的高德地图的key
        '&extensions=base&batch=false&location=' +
        latlng.lon +
        ',' +
        latlng.lat;
      $.ajax({
        url: url,
        success: function(result) {
          // commonAjax.ajaxSubmit(url, "GET", "", function (result) {
          if (result.status === '1') {
            _t.address = result.regeocode.formatted_address;
          } else {
            // errMsg.showError('1001');
          }
        }
      });
    },
    getLngLatLocation() {
      const _t = this;
      getAppLocation((data) => {
        if (data) {
          // var lnglat = gcj02towgs84(data.longitude, data.latitude);
          // _t.location(lnglat[0], lnglat[1])
          _t.location(data.longitude, data.latitude);
        }
      });
    }
  },
  created() {
    // 此处为调用精确定位之后，调取ip定位，可根据实际情况改写
  },
  mounted() {
    this.$nextTick(() => {
      this.initMap();
    });
  }
};
